/*	kd:
	Since the shop is executed from consoleplayer, if we just called something
	like GiveInventory, we'd certainly desync multiplayer games.
	
	That part is actually handled in this context, which does run for all
	players. Go figure, huh? Unfortunately, a net event doesn't solve this
	alone because they can only pass integers.
	
	Good for us, it's enough to do what we need, since the shop data
	will be the same for all players, we can just pass an index to what we'd
	like to buy or equip. */

class Gcs_Transactions : EventHandler {
	/*	This does the actual trading process, i. e. you have already done all
		checks necessary to determine, "yes, I can pay, yes, I can carry this,
		yes, the planets have aligned, ..." */
	
	void ConsoleBuyItem (uint player, uint shop_i, uint item_i) const {
		SendNetworkEvent("BuyItem", player, shop_i, item_i);
	}
	
	void ConsoleEquipItem (uint player, uint shop_i, uint item_i) const {
		SendNetworkEvent("EquipItem", player, shop_i, item_i);
	}
	
	/*	This is the function that actually happens. */
	
	private void NetBuyItem (uint player, uint shop_i, uint item_i) const {
		if(MAXPLAYERS <= player) {
			return;
		}
		
		Actor user = players [player].mo;
		
		if(user == NULL) {
			return;
		}
		
		let play_data = Gcs_PlayerData(Gcs_PlayerData.Find("Gcs_PlayerData"));
		
		if(play_data == NULL) {
			return;
		}
		
		Gc_Shop_Inv shop = play_data.m_shops [player].At(shop_i);
		
		if(!shop) {
			return;
		}
		
		// Do the trade.
		int price               = shop.Price       (item_i);
		int give                = shop.GiveAmount  (item_i);
		Gcs_ItemType handler    = shop.Handler     (item_i);
		class <Inventory> inv   = shop.InvClass    (item_i);
		
		handler.OnBuy(user, inv);
		user.GiveInventory(inv, give);
		
		if(!sv_infiniteinventory) {
			user.TakeInventory(shop.currency, price);
		}
	}
	
	private void NetEquipItem (uint player, uint shop_i, uint item_i) const {
		if(MAXPLAYERS <= player) {
			return;
		}
		
		Actor user = players [player].mo;
		
		if(user == NULL) {
			return;
		}
		
		let play_data = Gcs_PlayerData(Gcs_PlayerData.Find("Gcs_PlayerData"));
		
		if(play_data == NULL) {
			return;
		}
		
		Gc_Shop_Inv shop = play_data.m_shops [player].At(shop_i);
		
		if(!shop) {
			return;
		}
		
		// Do the equipment process.
		Gcs_ItemType handler    = shop.Handler     (item_i);
		class <Inventory> inv   = shop.InvClass    (item_i);
		handler.OnEquip(user, inv);
	}
	
	override void NetworkProcess (ConsoleEvent event) {
		if(event.ismanual) {
			return;
		}
		
		int p = event.player;
		
		if(p != event.args [0]) {
			return;
		}
		
		if(p < 0 || !players [p].mo) {
			return;
		}
		
		if(event.name ~== "BuyItem") {
			NetBuyItem(p, event.args [1], event.args [2]);
		}
		
		else if(event.name ~== "EquipItem") {
			NetEquipItem(p, event.args [1], event.args [2]);
		}
	}
}